<script lang="ts" setup>
import { PropType, ref } from 'vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
const emit = defineEmits(['submit', 'cancel', 'edit'])
const editStatus = ref(false)
const props = defineProps({
  title: {
    type: String,
    default: '标题'
  },
  tip: {
    type: String,
    default: ''
  },
  icon: {
    type: Boolean,
    default: false
  },
  iconClass: {
    type: String,
    default: 'icon-info-tip'
  },
  canOperate: {
    type: Boolean,
    default: false
  },
  /**
   * 提交函数 可以不传，传入需要是个promise
   */
  submit: {
    type: Function as PropType<() => Promise<any>>,
    default: null
  }
})

const handleCancel = () => {
  editStatus.value = false
  emit('cancel')
}

/**
 * 处理点击事件的函数
 * 根据编辑状态的不同执行不同的操作
 * 如果处于编辑状态，则提交更改；如果不处于编辑状态，则开始编辑
 */
const handleClick = () => {
  if (editStatus.value) {
    // 执行提交操作 在父组件中可以@submit去处理
    emit('submit')
    // 如果有传入的提交函数，则执行传入的提交函数，待传入的promise结束再改变编辑状态，否则直接改变
    if (props.submit) {
      props.submit().then(() => {
        editStatus.value = false
      })
    } else {
      editStatus.value = false
    }
    return
  }
  if (!editStatus.value) {
    emit('edit')
    editStatus.value = true
  }
}
</script>

<template>
  <div class="easy-title mb-[10px]">
    <div>
      <slot name="prefix">
        <span class="title">{{ title }}</span>
        <span v-if="tip && !icon" class="ml-[20px] text-sm text-[#8f8f8f]">{{
          tip
        }}</span>
        <span
          v-if="tip && icon"
          v-tippy="{
            content: tip,
            zIndex: 41000
          }"
          :class="[iconClass, 'ml-[20px]', 'text-[#8f8f8f]', 'cursor-pointer']"
        />
      </slot>
    </div>

    <div>
      <slot name="suffix">
        <template v-if="canOperate">
          <el-button v-show="editStatus" link @click="handleCancel">
            {{ t('button.cancelText') }}
          </el-button>
          <el-button type="primary" link @click="handleClick">
            {{ editStatus ? t('button.submitText') : t('button.editText') }}
          </el-button>
        </template>
      </slot>
    </div>
  </div>

  <div class="p-[10px]">
    <slot :status="editStatus" />
  </div>
</template>

<style lang="scss" scoped>
.easy-title .tip {
  margin-left: 20px;
  font-size: 14px;
  color: #8e8e8e;
}
</style>
